import {
	Inject
} from 'plugins'
import config from 'config';

@Inject('$scope', '$state', 'ui.dialog', 'ui.http', 'ui.api', 'MetaModelService')
export class MetaModel {
	constructor($scope, $state, dialog, http, api, service) {
		var dataSource = api.tree({
			scope: $scope,
			type: 'tree',
			url: 'category/treeCategory'
		});
		dataSource.bind('requestEnd', function() {
			var tree = $scope.tree;
			setTimeout(function() {
				var root = dataSource.at(0);
				var el = tree.findByUid(root.uid);
				tree.select(el);
			}, 0);
		});
		//	$scope.$on("kendoWidgetCreated", function(event, widget) {
		//		var tree = $scope.tree;
		//		if (widget === tree) {
		//			var dataSource = tree.dataSource;
		//			setTimeout(function() {
		//				var root = dataSource.at(0);
		//				var el = tree.findByUid(root.uid);
		//				tree.select(el);
		//			}, 0);
		//		}
		//	});

		$scope.treeReload = function() {
			api.treeReload.apply($scope, arguments);
		}

		var getTreeNode = $scope.getTreeNode = function() {
			return $scope.selectedTreeNode;
		}

		$scope.isNodeRoot = function() {
			var node = getTreeNode();
			return !node || ['-100', '-99', '-98', '-97'].indexOf(node.id) > -1 || node.isCube || node.hasChildren;
		}

		$scope.isNode = function() {
			var node = getTreeNode();
			return !node || ['-100', '-99', '-98', '-97'].indexOf(node.id) > -1;
		}

		$scope.isCubeRoot = function() {
			var node = getTreeNode();
			return node && node.isCube;
		}

		$scope.isChild = function() {
			var node = getTreeNode();
			return node && node.hasChildren;
		}


		$scope.add = service.add;
		$scope.edit = service.edit;
		$scope.remove = service.remove;

		$scope.select = function(state) {
			if (state) {
				if ($state.is(state)) {
					$state.reload(state);
				} else {
					$state.go(state);
				}
			}
		}

		$scope.changeNode = function(node) {
			$scope.selectedTreeNode = node;

			if ($scope.isNode()) {
				$scope.select('meta.model.types');
			} else {
				$scope.select('meta.model.list');
			}
		}
	}
}